package org.e_gold.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.e_gold.dao.SettledContractDAO;
import org.e_gold.model.SettledContract;
import org.e_gold.model.crawler.livescore.CEvent;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class SettledContractDAOImpl extends AbstractGenericDAO<SettledContract> implements SettledContractDAO {

	private static final Logger logger = Logger.getLogger(SettledContractDAOImpl.class);

	public SettledContractDAOImpl() {

		super(SettledContract.class);
	}

	@Override
	public void updateRunningToFalse(SettledContract contract) {

		logger.debug("Executing update contract[" + contract + "] to false");
		Query query = getCurrentSession().createSQLQuery(UPDATE_SETTED_CONTRACT_RUNNING_TO_FALSE).setLong("id_settled_contract", contract.getId());
		int i = query.executeUpdate();
		logger.debug("Updated contract [" + contract.getId() + "] result: " + i);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<SettledContract> getListRunningSettledContract() {

		List<SettledContract> retval = null;
		Criteria criteria = getCurrentSession().createCriteria(SettledContract.class);
		criteria.setFirstResult(0);
		criteria.add(Restrictions.eq(SettledContract.RUNNING, true));
		if (CollectionUtils.isNotEmpty(criteria.list())) {
			retval = criteria.list();
		}
		return retval;
	}

	public List<SettledContract> getNearlyContract(Date dFrom, Date dTo){
		List<SettledContract> lst = null;

		Criteria crit = getCurrentSession().createCriteria(CEvent.class);
		crit.add(Restrictions.between("insertTimeStamp", dFrom, dTo));

		List<CEvent> data = crit.list();
		List<CEvent> retList = new ArrayList<CEvent>();
		for(CEvent ce : data){
			retList.add(ce);
		}

		return lst;
	}

}
